Implementing Unit Tests | Pytest
Pytest is the built-in library provided by Python for testing in Python. It simplifies the process of writing and executing tests. Pytest supports unittest test cases execution. It has benefits like supporting built in assert statement, filtering of test cases, returning from last failing test etc.
We can install Pytest by writing the following command in the command prompt:
pip install pytest
Let’s start with a simple example. Here, we will make a file named as math_functions.py.
# math_functions.py
def add(x, y):
return x + y
def subtract(x, y):
return x - y
Now, we will make another file named as test_math_functions.py. We are making this file to perform testing using pytest using sample inputs.
# test_math_functions.py
import math_functions
def test_add():
assert math_functions.add(2, 3) == 5
assert math_functions.add(-1, 1) == 0
assert math_functions.add(0, 0) == 0
def test_subtract():
assert math_functions.subtract(5, 3) == 2
assert math_functions.subtract(0, 0) == 0
assert math_functions.subtract(-1, -1) == 0
To run these tests using pytest, navigate to the directory containing these files in your terminal and run:
pytest
Output:
Getting Started With Unit Testing in Python
In Python, unit tests are the segments of codes that are written to test other modules and files that we refer to as a unit. Python Unit Testing is a very important part of the software development process that helps us to ensure that the code works properly without any errors. In this article, we will learn about Python Testing with the help of examples and proper explanations.
Table of Content
- What is Python Unit Testing?
- The Assert Statement
- Implementing Unit Tests | Unittest
- Implementing Unit Tests | Pytest
- Implementing Unit Tests | Nose
- Implementing Unit Tests | Doctest
- How to Write Assertions in Python Testing
- More Advanced Testing Scenarios
- Automating the Execution of Tests